import * as types from '../actionTypes/todos';

const initialState = [
  { id: 1, text: '吃饭', done: false },
  { id: 2, text: '学习', done: true },
  { id: 3, text: '睡觉', done: false },
];

export const todos = (state = initialState, action) => {
  // 删除一个todo
  if (action.type === types.DEL_TODO) {
    return state.filter((item) => item.id !== action.payload);
  }

  // 切换todo状态
  if (action.type === types.TOGGLE_TODO) {
    // 修改原数组，不改变长度
    return state.map((item) => {
      // 修改的是谁
      if (item.id === action.payload) {
        return {
          ...item,
          done: !item.done,
        };
      }
      // 返回原来的数据
      return item;
    });
  }

  // 新增一个 todo
  if (action.type === types.ADD_TODO) {
    // const id = state.length === 0 ? 1 : state.length+1
    return [
      {
        id: state.length + 1,
        text: action.payload,
        done: false,
      },
      ...state,
    ];
  }

  // 修改（切换）全部任务的完成状态
  if (action.type === types.TOGGLE_ALL) {
    // return state.map(item => {
    //   return {
    //     ...item,
    //     done: action.payload
    //   }
    // })
    // 函数返回对象的简写
    return state.map((item) => ({ ...item, done: action.payload }));
  }

  // 没有匹配的action返回原数据
  return state;
};
